package com.hongfan.common.filter;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hongfan.common.constants.AuthConstant;
import com.hongfan.common.dto.AuthUserDto;
import lombok.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zcs
 * @since 2023/10/17
 */
@Component
public class AuthenticationFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, @NonNull HttpServletResponse response,@NonNull  FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(AuthConstant.USER_TOKEN_HEADER);
        if (StringUtils.hasText(token)) {
            String json = Base64.decodeStr(token);
            JSONObject jsonObject = JSON.parseObject(json);
            String principal = jsonObject.getString("userName");
            JSONArray jsonArray = jsonObject.getJSONArray("authorities");
            AuthUserDto authUserDto = new AuthUserDto();
            authUserDto.setLoginId(principal);
            authUserDto.setRoles(jsonArray.toString());
            request.setAttribute("AuthUserInfo",authUserDto);
        }
        filterChain.doFilter(request,response);
    }
}
